package com.netintech.process.leave.controller;


import com.netintech.common.utils.SecurityUtils;
import com.netintech.common.utils.poi.ExcelUtil;
import com.netintech.core.aspectj.lang.annotation.Log;
import com.netintech.core.aspectj.lang.enums.BusinessType;
import com.netintech.core.web.controller.BaseController;
import com.netintech.core.web.domain.RequestResult;
import com.netintech.core.web.page.TableDataInfo;
import com.netintech.process.leave.domain.BizLeaveAuditDto;
import com.netintech.process.leave.domain.BizLeaveVo;
import com.netintech.process.leave.service.IBizLeaveService;
import com.netintech.process.service.ProcessCommonService;
import com.netintech.project.system.domain.SysUser;
import org.activiti.engine.ActivitiTaskAlreadyClaimedException;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.apache.commons.lang3.BooleanUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.netintech.core.web.domain.RequestResult.error;
import static com.netintech.core.web.domain.RequestResult.success;

/**
 * 请假业务Controller
 *
 * @author admin
 */
@RestController
@RequestMapping("/process/leave")
public class BizLeaveController extends BaseController {

    private static final String MODULE_KEY = "leave";

    @Autowired
    private IBizLeaveService bizLeaveService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private ProcessCommonService processCommonService;

    /**
     * 查询请假业务列表
     */
    @PreAuthorize("@ss.hasPermi('process:leave:list')")
    @GetMapping("/list")
    public TableDataInfo list(BizLeaveVo bizLeave) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        if (!SysUser.isAdmin(sysUser.getUserId())) {
            bizLeave.setCreateBy(sysUser.getUserId().toString());
        }
        List<BizLeaveVo> list = bizLeaveService.selectBizLeaveList(bizLeave);
        return getDataTable(list);
    }

    /**
     * 导出请假业务列表
     */
    @PreAuthorize("@ss.hasPermi('process:leave:export')")
    @PostMapping("/export")
    public RequestResult export(BizLeaveVo bizLeave) {
        List<BizLeaveVo> list = bizLeaveService.selectBizLeaveList(bizLeave);
        ExcelUtil<BizLeaveVo> util = new ExcelUtil<BizLeaveVo>(BizLeaveVo.class);
        return util.exportExcel(list, MODULE_KEY);
    }


    /**
     * 新增保存请假业务
     */
    //@PreAuthorize("@ss.hasPermi('process:leave:add')")
    @Log(title = "请假业务", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public RequestResult addSave(@RequestBody BizLeaveVo bizLeave) {
        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        if (SysUser.isAdmin(userId)) {
            return error("新增申请失败：不允许管理员提交申请！");
        }
        return returnResult(bizLeaveService.insertBizLeave(bizLeave));
    }

    /**
     * 修改请假详情
     */
    @GetMapping("/edit/{id}")
    public RequestResult edit(@PathVariable("id") Long id) {
        BizLeaveVo bizLeave = bizLeaveService.selectBizLeaveById(id);
        return RequestResult.success(bizLeave);
    }

    /**
     * 修改保存请假业务
     */
    @PreAuthorize("@ss.hasPermi('process:leave:edit')")
    @Log(title = "请假业务", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    public RequestResult editSave(@RequestBody BizLeaveVo bizLeave) {
        return returnResult(bizLeaveService.updateBizLeave(bizLeave));
    }

    /**
     * 删除请假业务
     */
    @PreAuthorize("@ss.hasPermi('process:leave:remove')")
    @Log(title = "请假业务", businessType = BusinessType.DELETE)
    @DeleteMapping( "/remove/{id}")
    public RequestResult remove(@PathVariable("id") String id) {
        return returnResult(bizLeaveService.deleteBizLeaveByIds(id));
    }

    /**
     * 提交申请
     */
    @Log(title = "请假业务", businessType = BusinessType.UPDATE)
    @PostMapping( "/submitApply/{id}")
    public RequestResult submitApply(@PathVariable("id") Long id) {
        BizLeaveVo leave = bizLeaveService.selectBizLeaveById(id);
        String applyUserId = SecurityUtils.getUserIdString();
        bizLeaveService.submitApply(leave, applyUserId, MODULE_KEY);
        return success();
    }

    /**
     * 我的待办列表
     * @param bizLeave
     * @return
     */
    @PreAuthorize("@ss.hasPermi('process:leave:taskList')")
    @PostMapping("/taskList")
    public TableDataInfo taskList(BizLeaveVo bizLeave) {
        setPageParam();
        List<BizLeaveVo> list = bizLeaveService.findTodoTasks(bizLeave, SecurityUtils.getUsername(), MODULE_KEY);
        return getDataTable(list);
    }

    /**
     * 加载审批弹窗
     * @param taskId
     * @return
     */
    @GetMapping("/showVerifyDialog/{taskId}")
    public RequestResult showVerifyDialog(@PathVariable("taskId") String taskId) {
        Map<String, Object> result = new HashMap<>();
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        String processInstanceId = task.getProcessInstanceId();
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
        BizLeaveVo bizLeave = bizLeaveService.selectBizLeaveById(new Long(processInstance.getBusinessKey()));
        bizLeave.setTaskId(taskId);
        result.put("bizLeave", bizLeave);
        String verifyName = task.getTaskDefinitionKey().substring(0, 1).toUpperCase() + task.getTaskDefinitionKey().substring(1);
        result.put("page", verifyName);
        return RequestResult.success(result);
    }

    /**
     * 完成任务
     *
     * @return
     */
    @RequestMapping(value = "/complete", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public RequestResult complete(@RequestBody BizLeaveAuditDto leaveAuditDto) throws ActivitiTaskAlreadyClaimedException {
        boolean saveEntityBoolean = false;
        Map<String, Object> variables = new HashMap<String, Object>();
        String page = leaveAuditDto.getPage();
        String isAgree = leaveAuditDto.getIsAgree();
        String comment = leaveAuditDto.getComment();
        if("DeptLeaderVerify".equals(page)){//部门经理页面
            variables.put("deptLeaderApproved", BooleanUtils.toBoolean(isAgree));
        }else if("HrVerify".equals(page)){
            variables.put("hrApproved", BooleanUtils.toBoolean(isAgree));
        }else if("ModifyApply".equals(page)){
            variables.put("reApply", BooleanUtils.toBoolean(isAgree));
            saveEntityBoolean = true;
        }else if("ReportBack".equals(page)){
            variables.put("realityStartTime", leaveAuditDto.getRealityStartTime());
            variables.put("realityEndTime", leaveAuditDto.getRealityEndTime());
        }
        if(saveEntityBoolean){
            //调整申请
            BizLeaveVo bizLeaveVo = new BizLeaveVo();
            BeanUtils.copyProperties(leaveAuditDto, bizLeaveVo);
            bizLeaveService.updateBizLeave(bizLeaveVo);
        }
        processCommonService.complete(leaveAuditDto.getTitle(), leaveAuditDto.getReason(), leaveAuditDto.getInstanceId(), saveEntityBoolean,
                MODULE_KEY, leaveAuditDto.getTaskId(), variables, comment);
        return success("任务已完成");
    }

    /**
     * 自动绑定页面字段
     */
    @ModelAttribute("preloadLeave")
    public BizLeaveVo getLeave(@RequestParam(value = "id", required = false) Long id) {
        if (id != null) {
            return bizLeaveService.selectBizLeaveById(id);
        }
        return new BizLeaveVo();
    }

    /**
     * 我的已办列表
     * @param bizLeave
     * @return
     */
    @PreAuthorize("@ss.hasPermi('process:leave:taskDoneList')")
    @PostMapping("/taskDoneList")
    @ResponseBody
    public TableDataInfo taskDoneList(BizLeaveVo bizLeave) {
        setPageParam();
        List<BizLeaveVo> list = bizLeaveService.findDoneTasks(bizLeave, SecurityUtils.getUsername());
        return getDataTable(list);
    }

}
